package com.hxzy.service.system.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.consts.UserConstants;
import com.hxzy.dto.system.SysRoleSearchDTO;
import com.hxzy.entity.system.SysRole;
import com.hxzy.mapper.system.SysRoleMapper;
import com.hxzy.service.system.SysRoleService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 角色业务逻辑实现
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    /**
     * 查询用户拥有的权限
     * @param userId
     * @return
     */
    @Override
    public Set<String> searchUserOwnRole(Long userId) {

        return this.baseMapper.searchUserOwnRole(userId);
    }

    @Override
    public boolean addAndGrantMenu(SysRole role, List<Long> permsList) {
        //1、新增
        boolean result=super.save(role);
        if(result ){
            //2、分配了权限
            if(permsList!=null && permsList.size()>0){
                this.baseMapper.grantMenuPerms( role.getRoleId(), permsList);
            }
        }
        return result;
    }

    @Override
    public boolean editAndGrantMenu(SysRole role, List<Long> permsList) {
        //1、保存
        boolean result = super.updateById(role);
        if(result){

            //2、先删除已有权限
            this.baseMapper.deleteMenuByRoleId(role.getRoleId());

            //3、分配了权限
            if(permsList!=null && permsList.size()>0){
                this.baseMapper.grantMenuPerms( role.getRoleId(), permsList);
            }
        }
        return result;
    }

    @Override
    public List<SysRole> search(SysRoleSearchDTO sysRoleSearchDTO) {
        return this.baseMapper.search( sysRoleSearchDTO);
    }



    @Override
    public boolean isAdmin(Long userId) {
        Set<String> roles = this.baseMapper.searchUserOwnRole(userId);
        String userRole = roles.stream().filter(role -> role.equals(UserConstants.SUPER_MAN_NAME)).findAny().orElse("");
        return StrUtil.isNotBlank(userRole);
    }
}
